//
//  FIPlayViewController.m
//  OpenglPing
//
//  Created by protocal 100TV on 12-11-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FIPlayViewController.h"
#import "FIOperationTest.h"
#import "Persion.h"

@interface TestKvo()

@end
@implementation TestKvo
@synthesize name=_name;

- (void)changeName
{
    _name=@"doudou";
}
@end

@implementation TestKvoMaster

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"name"]) {
        NSLog(@"change happen,old:%@ new:%@",
              [change objectForKey:NSKeyValueChangeOldKey],
              [change objectForKey:NSKeyValueChangeNewKey]);
    }
}

@end


///////////////////////////****player****//////////////////////////////////

@implementation CustomPlayerView
+(Class)layerClass{
    return [AVPlayerLayer class];
}
-(AVPlayer*)player{
    return [(AVPlayerLayer*)[self layer] player];
}
-(void)setPlayer:(AVPlayer *)thePlayer{
    return [(AVPlayerLayer*)[self layer]setPlayer:thePlayer];
}
@end
//////////////////
@interface FIPlayViewController ()

@end

@implementation FIPlayViewController

//@synthesize mPlayer;

- (void)dealloc
{
    [_movePlayerView release];
    [_play release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    BOOL isTestKVO = NO;
    
    if (isTestKVO) {
        TestKvo * p = [[TestKvo alloc] init];
        TestKvoMaster * pm = [[TestKvoMaster alloc] init];
        [p addObserver:pm forKeyPath:@"name" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
        [p addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
        
        NSLog(@"p.name is %@",p.name);
        [p setValue:@"name kvc" forKey:@"name"];
        NSLog(@"p name get by kvc is %@",[p valueForKey:@"name"]);
        p.name=@"red";
        [p changeName]; //can't be notify
        
        [p setValue:@"12" forKeyPath:@"age"];
        NSString * age = [p valueForKeyPath:@"age"];
        NSLog(@"age:%@", age);
    }
    
    BOOL isTestOperation = NO;
    if (isTestOperation) {
        queue = [[NSOperationQueue alloc] init];
        
        NSInteger index = 0;
        FIOperationTest * oT1 = [[[FIOperationTest alloc] init] autorelease];
        oT1.nIndex = index++;
        [queue addOperation:oT1];
        
        oT1 = [[[FIOperationTest alloc] init] autorelease];
        oT1.nIndex = index++;
        [queue addOperation:oT1];
        
        oT1 = [[[FIOperationTest alloc] init] autorelease];
        oT1.nIndex = index++;
        if ([[queue operations] count] > 1) {
            FIOperationTest * tt = [[queue operations] lastObject];
            [oT1 addDependency:tt];
        }
        
        [queue addOperation:oT1];
    }
    
    BOOL isCoreData = YES;
    if (isCoreData) {
//        NSLog(@">>start app ");
//        Persion *person=(Persion *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[self managedObjectContext]];
//        person.name=@"张三";
//        
//        NSError *error;
//        
//        if (![[self managedObjectContext] save:&error]) {
//            NSLog(@"error!");
//        }else {
//            NSLog(@"save person ok.");
//        }
//        
//        NSFetchRequest *request=[[NSFetchRequest alloc] init];
//        NSEntityDescription *entity=[NSEntityDescription entityForName:@"Person" inManagedObjectContext:[self managedObjectContext]];
//        [request setEntity:entity];
//        
//        NSArray *results=[[[self managedObjectContext] executeFetchRequest:request error:&error] copy];
//        
//        for (Persion *p in results) {
//            NSLog(@">> p.id: %i p.name: %@", p.id, p.name);
//        }
        
//        NSString *fp = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file_fuck.txt"];
//        NSString *test = @"something";
//        [test writeToFile:fp atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //在这里获取应用程序Documents文件夹里的文件及文件夹列表
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDir = [documentPaths objectAtIndex:0];
        NSError *error = nil;
        NSArray *fileList = [[NSArray alloc] init];
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];
        
        NSMutableArray *dirArray = [[NSMutableArray alloc] init];
        BOOL isDir = NO;
        //在上面那段程序中获得的fileList中列出文件夹名
        for (NSString *file in fileList) {
            NSString *path = [documentDir stringByAppendingPathComponent:file];
            [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
            if (isDir) {
                [dirArray addObject:file];
            }
            isDir = NO;
        }
        NSLog(@"Every Thing in the dir:%@", fileList);
        NSLog(@"All folders:%@", dirArray);
    }
    
    [self initPlayer];
}
- (void)setPlayUrl:(NSString*)url
{
    m_play_url = url;
}
- (void)initPlayer
{
    NSURL * m_url = [[NSURL alloc] initWithString:@"http://data.vod.itc.cn/tv/20121116/669425-868855-e4370b1c-8ce3-43b8-86a2-db6a7aede4c0.mp4?new=/43/140/ZIzUtgVYBRjaQM1bqsEXH6.mp4"];
////    player = [[AVPlayer alloc] initWithURL:m_url];
////    [player play];
    //使用playerItem获取视频的信息，当前播放时间，总时间等
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"9girls" ofType:@"mp4"];
    NSLog(@"data:%@", filePath);
    NSLog(@"url:%@", m_play_url);

    if (m_play_url != nil) {
        m_play_url = filePath;
    }
    NSURL *sourceMovieURL = [NSURL fileURLWithPath:m_play_url];
    
    AVAsset *movieAsset	= [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.view.layer.bounds;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.view.layer addSublayer:playerLayer];
    [player play];
}

-(void)moviePlayDidEnd:(NSNotification*)notification{
    [self doneClick:nil];
}
-(IBAction)doneClick:(id)sender{
    [_movePlayerView.player pause];
    [self dismissModalViewControllerAnimated:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"name"]) {
        NSLog(@"view,old:%@ new:%@",
              [change objectForKey:NSKeyValueChangeOldKey],
              [change objectForKey:NSKeyValueChangeNewKey]);
        if ([[change objectForKey:NSKeyValueChangeNewKey] isEqualToString:@"red"]) {
            self.view.backgroundColor = [UIColor redColor];
        } else {
            self.view.backgroundColor = [UIColor grayColor];
        }
    } else if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *playerItem = (AVPlayerItem*)object;
        if (playerItem.status==AVPlayerStatusReadyToPlay) {
            //[loadingView hide:YES];
        }
    }
}

- (void)viewDidUnload
{
    [self setMovePlayerView:nil];
    [self setPlay:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

- (IBAction)onplay:(id)sender {
    [_movePlayerView.player play];
}


@end
